package com.ziq.zcamp

import com.ziq.base.base.hilt.ConfigModule
import com.ziq.base.base.hilt.GlobalConfigModule
import com.ziq.zcamp.manager.UserManager
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import okhttp3.Response
import java.io.UnsupportedEncodingException
import java.net.URLEncoder

class GlobalConfiguration : ConfigModule {
    override fun applyCustomConfig(globalConfigModule: GlobalConfigModule) {
        globalConfigModule.isDebug = BuildConfig.DEBUG
    }

    override fun setupOkHttpClient(builder: OkHttpClient.Builder) {
        builder.addInterceptor(object : Interceptor {
            override fun intercept(chain: Interceptor.Chain): Response {
                val oldRequest = chain.request()
                val newUrl = oldRequest.url.newBuilder().apply {
                    val atomMap = UserManager.instance.getAtomMap()
                    val entryIterator = atomMap.entries.iterator()
                    while (entryIterator.hasNext()) {
                        val entry = entryIterator.next()
                        if (null == entry.value) {
                            continue
                        }
                        val k = entry.key
                        val v = entry.value.toString()
                        setQueryParameter(k, v)
                    }
                }.build()
                val newRequest = oldRequest.newBuilder().url(newUrl).build()
                return chain.proceed(newRequest)
            }
        })
    }
}
